package com.roc.web.action.black;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.BlackList;
import com.roc.pojo.Operators;
import com.roc.pojo.susesMerinfo;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.service.black.IBlackService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.web.action.susMerinfo.SusMerinfoSearchCondition;

@Component
@Scope("prototype")
@Namespace("/black")
public class BlackListAction extends PaginationBaseAction{
	private Logger logger=LogManager.getLogger(BlackListAction.class);
	
	private BlackListSearchCondition searchCondition;
	private BlackList black;
	
	private InputStream excelFile;
	private String  excelName;
	
	private File upload;
		
	
	@Autowired
	IExcelService excelService;
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IBlackService blackService;
	
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/black/blackQuery.jsp")
    })
	public String init(){
		return SUCCESS;
	}
	
	@Action(value = "queryBlack", 
			results = { @Result(name = "success", location = "/pages/black/blackQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryBlack(){
	
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		if(searchCondition==null){
			searchCondition=(BlackListSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new BlackListSearchCondition();
			}
		}
		try {
				
			init();
			
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<BlackList> msList=new ArrayList<BlackList>();
			dealWith(msList,searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("blackList", msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}
	@Action(value = "addJsp", 
			results = { @Result(name = "success", location = "/pages/black/addBlack.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addJsp(){
		return SUCCESS;
	}
	
	@Action(value = "addBlack", 
			results = { @Result(name = "success", location = "/pages/black/blackQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addBlack(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try{
			blackService.addBlack(black, op);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return queryBlack();
	}
	
	@Action(value = "startUsing", 
			results = { @Result(name = "success", location = "/pages/black/blackQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String startUsing(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(black==null){
			addActionMessage("查询错误");
			return queryBlack();
		}

		try{
			black=blackService.queryByNo(black.getAcctNo(), black.getCardNo(), black.getLicenseNo());
			blackService.changeStatus(black, "Y", op);	
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return queryBlack();
	}
	
	@Action(value = "NoStartUsing", 
			results = { @Result(name = "success", location = "/pages/black/blackQuery.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String NoStartUsing(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		if(black==null){
			addActionMessage("查询错误");
			return queryBlack();
		}
		
		try{
			black=blackService.queryByNo(black.getAcctNo(), black.getCardNo(), black.getLicenseNo());
			blackService.changeStatus(black, "N", op);	
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return queryBlack();
	}
	
	
	@Action(value="blackExport",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/susMerinfo/query.jsp") }) 
	public String blackExport(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(searchCondition==null){
			searchCondition=(BlackListSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new BlackListSearchCondition();
			}
		}
		try{

			//searchCondition.setAgentId(op.getId());
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<BlackList> msList=new ArrayList<BlackList>();
			dealWith(msList,searchRsList);
			
			HSSFWorkbook work=excelService.blackListExcel(msList);
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
		}catch(Exception e){
			logger.info("######导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public String getExcelName() {
		String excelName="黑名单"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	
	private List<BlackList> dealWith(List<BlackList> msList,List<Object> searchRsList){
		if(searchRsList.size()>0 && searchRsList!=null){
			
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				BlackList  msb=new BlackList(); 
				msb.setAcctNo(Constance.Null2EmptyTrim(obj[0]));
				msb.setCardNo(Constance.Null2EmptyTrim(obj[1]));
				msb.setLicenseNo(Constance.Null2EmptyTrim(obj[2]));
				msb.setMid(Constance.Null2EmptyTrim(obj[3]));
				msb.setTermId(Constance.Null2EmptyTrim(obj[4]));
				msb.setAddType(Constance.Null2EmptyTrim(obj[5]));
				msb.setUnlockTimes(Long.parseLong(Constance.Null2EmptyTrim(obj[6])));
				msb.setIsused(Constance.Null2EmptyTrim(obj[7]));
				msb.setRemark(Constance.Null2EmptyTrim(obj[8]));
				msb.setDtCreate(Constance.Null2EmptyTrim(obj[9]));
				msb.setDtLastmod(Constance.Null2EmptyTrim(obj[10]));
				msb.setOperators(Constance.Null2EmptyTrim(obj[11]));
				
				if(msb.getAddType().equals("H1")){
					msb.setAddType("调单拒付");
				}else if(msb.getAddType().equals("H2")){
					msb.setAddType("非法经营");
				}else if(msb.getAddType().equals("H3")){
					msb.setAddType("套现嫌疑");
				}
				msList.add(msb);
			}
		}
		return msList;
		
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BLACK_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BLACK_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public BlackListSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(BlackListSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public BlackList getBlack() {
		return black;
	}

	public void setBlack(BlackList black) {
		this.black = black;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	
	
}
